import React, { useState } from "react"
import { UploadOutlined, InboxOutlined } from "@ant-design/icons"
import { Button, Upload, Modal, App } from "antd"
import { proxyReplace } from "@/http/proxyReplace"
import userInfoStore from "@/store/userInfo/index"
import { concatUrl, downloadFile } from "@/utils/file-utils"
const { Dragger } = Upload

function UniversalUpload({ listType = "text", isDragger = false, getFileInfo, ...restProps }) {
  const { modal, message } = App.useApp()
  const { getToken } = userInfoStore()
  const [fileList, setFileList] = useState([])
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewImage, setPreviewImage] = useState("")
  const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }

  function updateFile(fileList) {
    setFileList(fileList)
    const newFileListLast = fileList.map((v) => {
      if (Object.prototype.hasOwnProperty.call(v, "response")) {
        let url = ""
        if (v.response.data[0]?.fileType !== 1) {
          url =
            "http://bjbztest.oss-cn-qingdao.aliyuncs.com/fssc-core/image/documentII.png?x-oss-process=image/resize,m_pad,h_200,w_200,color_FFFFFF"
        } else {
          if (v.response.data[0]?.path.indexOf("http") === 0) {
            url = v.response.data[0]?.path
          } else {
            url = concatUrl(v.response.data[0]?.path)
          }
        }
        return {
          url,
          fileName: v.response.data[0]?.fileName,
          fileType: v.response.data[0]?.fileType,
          size: v.size
        }
      } else {
        return v
      }
    })
    getFileInfo(newFileListLast)
    message.success(`文件操作成功`)
  }

  const removeItem = (arr, removeKey) => arr.filter((i) => i.name !== removeKey)
  // 上传组件配置项
  const props = {
    listType,
    action: proxyReplace("/api/PublicFileController/uploadFileServerCoudWebWithType"),
    headers: {
      Authorization: getToken()
    },
    showUploadList: {
      showDownloadIcon: true
    },
    ...restProps,
    onChange(info) {
      if (info.file?.status === "removed") {
        const handleFileList = removeItem(fileList, info.file.name)
        updateFile(handleFileList)
      }
      if (info.file?.status === "done") {
        updateFile(info.fileList)
      } else if (info.file?.status === "error") {
        message.error(`上传失败`)
      }
    },
    // 预览图片
    onPreview: async (file) => {
      const regx = /(gif|jpg|jpeg|png|bmp|svg\+xml|webp|svg|GIF|JPG|JPEG|PNG|BMP|WEBP|SVG)$/
      const fileType = file.type?.split("/")[1]
      if (!file.url && regx.test(fileType)) {
        file.preview = await getBase64(file.originFileObj)
        setPreviewImage(file.url || file.preview)
        setPreviewOpen(true)
      } else if (/(avi|mp4|AVI|MP4|pdf|PDF)$/.test(fileType)) {
        window.open(file.response?.data[0].path)
      }
    },
    // 下载文件
    onDownload: (file) => {
      const { path, fileName } = file.response.data[0]
      downloadFile(path, fileName)
    },
    // 删除文件询问
    onRemove: (file) => {
      return new Promise((resolve) => {
        modal.confirm({
          title: "删除提示",
          content: "确认删除当前项吗？",
          onOk() {
            resolve(true)
            props.onChange(file)
          },
          onCancel() {
            resolve(false)
          }
        })
      })
    }
  }

  return (
    <>
      {isDragger ? (
        <Dragger {...props}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">Click or drag file to this area to upload</p>
        </Dragger>
      ) : (
        <Upload {...props}>
          {listType === "picture-card" ? (
            <div>
              <UploadOutlined className="text-20px" />
              <div className="mt-8px">点击上传</div>
            </div>
          ) : (
            <Button icon={<UploadOutlined />}>点击上传</Button>
          )}
        </Upload>
      )}
      <Modal
        title="查看图片"
        footer={null}
        open={previewOpen}
        onCancel={() => setPreviewOpen(false)}
      >
        <img className="w-full" alt="example" src={previewImage} />
      </Modal>
    </>
  )
}

export default UniversalUpload
